// 测试常量
export const TEST_CONSTANTS = {
  MOCK_TOKEN: 'mock-jwt-token-12345',
  MOCK_REFRESH_TOKEN: 'mock-refresh-token-67890',
  
  // 用户相关常量
  DEFAULT_USER_ID: 'test-user-123',
  DEFAULT_USERNAME: 'testuser',
  DEFAULT_EMAIL: 'test@example.com',
  DEFAULT_PHONE: '13800138000',
  
  // 租户相关常量
  DEFAULT_TENANT_ID: 'tenant-test-123',
  DEFAULT_TENANT_NAME: '测试租户',
  DEFAULT_TENANT_CODE: 'TEST_TENANT',
  
  // 组织相关常量
  DEFAULT_ORG_ID: 'org-test-123',
  DEFAULT_ORG_NAME: '测试组织',
  DEFAULT_ORG_CODE: 'TEST_ORG',
  
  // API endpoints
  API_ENDPOINTS: {
    LOGIN: '/api/auth/login',
    LOGOUT: '/api/auth/logout',
    REFRESH: '/api/auth/refresh',
    TENANTS: '/api/tenants',
    ORGANIZATIONS: '/api/organizations',
    USERS: '/api/users',
    ROLES: '/api/roles',
    PERMISSIONS: '/api/permissions',
  },
  
  // Test timeouts
  TIMEOUTS: {
    SHORT: 1000,
    MEDIUM: 3000,
    LONG: 5000,
  }
};

// Mock数据工厂
export class MockDataFactory {
  static createUser(overrides = {}) {
    return {
      id: TEST_CONSTANTS.DEFAULT_USER_ID,
      username: TEST_CONSTANTS.DEFAULT_USERNAME,
      email: TEST_CONSTANTS.DEFAULT_EMAIL,
      profile: {
        fullName: '测试用户',
        phoneNumber: TEST_CONSTANTS.DEFAULT_PHONE,
        avatar: '',
        department: '技术部',
        position: '开发工程师'
      },
      tenants: [MockDataFactory.createTenant()],
      organizations: [MockDataFactory.createOrganization()],
      roles: [MockDataFactory.createRole()],
      permissions: ['user:read', 'user:write'],
      status: 'active' as const,
      lastLoginAt: new Date().toISOString(),
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      ...overrides
    };
  }

  static createTenant(overrides = {}) {
    return {
      id: TEST_CONSTANTS.DEFAULT_TENANT_ID,
      name: TEST_CONSTANTS.DEFAULT_TENANT_NAME,
      code: TEST_CONSTANTS.DEFAULT_TENANT_CODE,
      domain: 'test.example.com',
      status: 'active' as const,
      subscription: {
        plan: 'enterprise' as const,
        status: 'active' as const,
        startDate: '2024-01-01T00:00:00Z',
        expiresAt: '2024-12-31T23:59:59Z',
        features: ['multi_org', 'advanced_auth', 'api_access']
      },
      settings: {
        allowSelfRegistration: true,
        requireEmailVerification: true,
        sessionTimeout: 8,
        maxLoginAttempts: 5,
        enableAuditLog: true,
        enableDataExport: true
      },
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      ...overrides
    };
  }

  static createOrganization(overrides = {}) {
    return {
      id: TEST_CONSTANTS.DEFAULT_ORG_ID,
      name: TEST_CONSTANTS.DEFAULT_ORG_NAME,
      code: TEST_CONSTANTS.DEFAULT_ORG_CODE,
      description: '这是一个测试组织',
      tenantId: TEST_CONSTANTS.DEFAULT_TENANT_ID,
      parentId: null,
      level: 1,
      sort: 1,
      status: 'active' as const,
      settings: {
        enableDepartmentTree: true,
        enablePositionManagement: true,
        dataIsolation: 'organization' as const,
        allowCrossDepartmentAccess: false
      },
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      ...overrides
    };
  }

  static createRole(overrides = {}) {
    return {
      id: 'role-test-123',
      name: '测试角色',
      code: 'TEST_ROLE',
      description: '这是一个测试角色',
      type: 'custom' as const,
      level: 1,
      permissions: ['user:read', 'user:write'],
      tenantId: TEST_CONSTANTS.DEFAULT_TENANT_ID,
      organizationId: TEST_CONSTANTS.DEFAULT_ORG_ID,
      status: 'active' as const,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      ...overrides
    };
  }

  static createPermission(overrides = {}) {
    return {
      id: 'permission-test-123',
      name: '测试权限',
      code: 'test:permission',
      description: '这是一个测试权限',
      module: 'test',
      action: 'read',
      resource: 'test',
      status: 'active' as const,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      ...overrides
    };
  }

  static createDepartment(overrides = {}) {
    return {
      id: 'dept-test-123',
      name: '测试部门',
      code: 'TEST_DEPT',
      description: '这是一个测试部门',
      parentId: null,
      level: 1,
      sort: 1,
      managerIds: [],
      tenantId: TEST_CONSTANTS.DEFAULT_TENANT_ID,
      organizationId: TEST_CONSTANTS.DEFAULT_ORG_ID,
      status: 'active' as const,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      ...overrides
    };
  }

  static createPosition(overrides = {}) {
    return {
      id: 'position-test-123',
      name: '测试岗位',
      code: 'TEST_POSITION',
      description: '这是一个测试岗位',
      departmentId: 'dept-test-123',
      level: 1,
      sort: 1,
      requirements: [],
      responsibilities: [],
      tenantId: TEST_CONSTANTS.DEFAULT_TENANT_ID,
      organizationId: TEST_CONSTANTS.DEFAULT_ORG_ID,
      status: 'active' as const,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      ...overrides
    };
  }

  static createAuditLog(overrides = {}) {
    return {
      id: 'audit-test-123',
      action: 'user.login',
      description: '用户登录系统',
      level: 'info' as const,
      userId: TEST_CONSTANTS.DEFAULT_USER_ID,
      userName: '测试用户',
      tenantId: TEST_CONSTANTS.DEFAULT_TENANT_ID,
      organizationId: TEST_CONSTANTS.DEFAULT_ORG_ID,
      ip: '127.0.0.1',
      userAgent: 'Mozilla/5.0 Test Browser',
      metadata: {},
      createdAt: new Date().toISOString(),
      ...overrides
    };
  }

  static createPaginatedResponse<T>(items: T[], page = 1, pageSize = 10) {
    const total = items.length;
    const totalPages = Math.ceil(total / pageSize);
    const startIndex = (page - 1) * pageSize;
    const endIndex = Math.min(startIndex + pageSize, total);
    const paginatedItems = items.slice(startIndex, endIndex);

    return {
      items: paginatedItems,
      total,
      page,
      pageSize,
      totalPages,
      hasNext: page < totalPages,
      hasPrev: page > 1
    };
  }

  static createApiError(status = 500, message = 'Internal Server Error') {
    return {
      status,
      message,
      code: `ERROR_${status}`,
      timestamp: new Date().toISOString()
    };
  }
}

// 测试助手函数
export class TestHelpers {
  /**
   * 等待指定时间
   */
  static async sleep(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  /**
   * 创建延迟的Promise
   */
  static createDelayedPromise<T>(value: T, delay: number): Promise<T> {
    return new Promise(resolve => {
      setTimeout(() => resolve(value), delay);
    });
  }

  /**
   * 创建失败的Promise
   */
  static createRejectedPromise(error: Error | string, delay = 0): Promise<never> {
    return new Promise((_, reject) => {
      setTimeout(() => {
        reject(typeof error === 'string' ? new Error(error) : error);
      }, delay);
    });
  }

  /**
   * 模拟表单提交
   */
  static createFormSubmissionEvent(formData: Record<string, any>) {
    return {
      preventDefault: jest.fn(),
      target: {
        elements: Object.keys(formData).reduce((acc, key) => {
          acc[key] = { value: formData[key] };
          return acc;
        }, {} as any)
      }
    };
  }

  /**
   * 生成随机字符串
   */
  static generateRandomString(length = 8): string {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  }

  /**
   * 生成随机数字
   */
  static generateRandomNumber(min = 0, max = 100): number {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
}